import Monitor
import requests
import sys
import json
import subprocess
import html
import os
import shutil

configUrl = 'http://172.45.33.200/api/getconfig/{0}'
updateUrl = 'http://172.45.33.200/api/setrecord/{0}'

def doUpdateResult(result, id):
    r = requests.post(updateUrl.format(id), data={'info': json.dumps(result)})

def getRecord(id):
    r = requests.get(configUrl.format(id))
    if r:
        config = json.loads(r.text)['data']
        return config
    else:
        return False;

def main(argv):
    #1 Get config
    if len(argv) < 2:
        print('Usage:\n\tpython3 {0} recordId'.format(argv[0]))
        exit()
    rid, config = argv[1], getRecord(argv[1])
    result = {}
    result['status'], result['compileinfo'] = 8, ''
    result['time'] = result['memory'] = 0
    
    #2 Compile
    if os.path.isdir('/tmp/exec') is False:
        os.mkdir('/tmp/exec')
    with open('/tmp/exec/'+config['compile']['progName'], 'w') as prog:
        prog.write(html.unescape(config['code']))

    if config['compile']['intLang'] is True:
        pass
    else:
        compiler = subprocess.Popen(config['compile']['compile'], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        compiler.wait()
        result['compileinfo'] = compiler.stdout.read() + compiler.stderr.read()
        if type(result['compileinfo']) is bytes:
            result['compileinfo'] = result['compileinfo'].decode('UTF-8')
        if compiler.returncode:
            result['status'] = 4
            doUpdateResult(result, rid)
            exit()

    result['testpoints'] = []
    for testpoint in config['data']['testpoints']:
        result['testpoints'].append({'status': 8, 'info': '', 'time': 0, 'memory': 0})
    doUpdateResult(result, rid)
    for testpoint in config['data']['testpoints']:
        result['testpoints'][testpoint['id']] = Monitor.main(['', config['compile']['exec'], testpoint['input'], testpoint['output'], testpoint['time'], testpoint['memory'], testpoint['comparer']])
        result['time'] += result['testpoints'][testpoint['id']]['time']
        result['memory'] += result['testpoints'][testpoint['id']]['memory']
        doUpdateResult(result, rid)
    for testpoint in result['testpoints']:
        if testpoint['status'] is not 1:
            result['status'] = testpoint['status']
            break
        else:
            result['status'] = 1
    doUpdateResult(result, rid) 
    shutil.rmtree('/tmp/exec')
    
    return result

if __name__ == '__main__':
    main(sys.argv)